package com.geeklan.smart.data.remote.oss;

import android.content.Context;

import com.alibaba.sdk.android.oss.*;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.*;

public class FileUploader {
    public static void uploadFile(Context context, String filePath,UploadCallback uploadCallback) {
        OSS oss = OSSManager.getOSSClient(context);
        String objectKey = ObjectKeyGenerator.generateObjectKey(filePath);
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(OSSManager.BUCKET_NAME, objectKey, filePath);

        // 异步上传
        oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                // 获取上传的 Object Key
                String objectKey = request.getObjectKey();

                // 构造文件的完整访问 URL
                String fileUrl = "https://" + OSSManager.BUCKET_NAME + "." + OSSManager.ENDPOINT + "/" + objectKey;

                // 返回文件链接
                System.out.println("File uploaded successfully. URL: " + fileUrl);

                uploadCallback.onUploadSuccess(fileUrl);
                // 上传成功
                System.out.println("Upload Success!");
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 上传失败
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    System.out.println("ErrorCode: " + serviceException.getErrorCode());
                    System.out.println("RequestId: " + serviceException.getRequestId());
                    System.out.println("HostId: " + serviceException.getHostId());
                    System.out.println("RawMessage: " + serviceException.getRawMessage());
                }
                uploadCallback.onUploadFailure();
            }
        });
    }
}

